// pages/player/player.js

// 创建音乐播放器实例
const audioCtx = wx.createInnerAudioContext();

Page({

  /**
   * Page initial data
   */
  data: {
    cover:'', // 背景图
    title:'', // 标题
    author:'', // 作者
    index:0, // 当前索引
    isPlaying:false, // 播放状态
    dataArray: [ //乐曲信息
      {
        "audio" : '/resources/audio/1.mp3',
        "cover" : '/resources/cover/1.jpg',
        "title" : 'test music',
        "author" : 'janson',
      },
      {
        "audio" : '/resources/audio/2.mp3',
        "cover" : '/resources/cover/2.jpg',
        "title" : 'test music 2',
        "author" : 'janson Y',
      },
    ]
  },

  /**
   * Lifecycle function--Called when page load
   */
  onLoad(options) {
    this.setupUI(0);
    audioCtx.autoplay = false;
    // 播放事件监听
    audioCtx.onPlay(() => {
      console.log("监听到播放操作");
      this.setData({
        isPlaying: true
      });
    });
    // 暂停事件监听
    audioCtx.onPause(() => {
      console.log("监听到暂停操作");
      this.setData({
        isPlaying: false
      });
    });
  },  

  // 设置页面元素
  setupUI(index) {
    var tempData = this.data.dataArray[index]
    this.setData({
      cover:tempData['cover'],
      title:tempData['title'],
      author:tempData['author'],
      index:index
    }),
    audioCtx.src = tempData['audio']
  },

  // 上一首
  previousTap() {
    let index = this.data.index
    if (index==0) {
      index = this.data.dataArray.length - 1
    } else {
      index--
    }
    this.setupUI(index)
    audioCtx.play()
  },

  // 下一首
  nextTap() {
    let index = this.data.index
    if (index==this.data.dataArray.length-1) {
      index = 0
    } else {
      index++
    }
    this.setupUI(index)
    audioCtx.play()
  },

  // 播放
  playTap() {
    console.log(this.data.isPlaying)
    if(this.data.isPlaying) {
      audioCtx.pause();
    } else {
      audioCtx.play();
    }
  }
})